﻿using General.Entities.Data;
using General.Framework;
using General.Framework.Admin;
using General.Mvc.Filters;
using General.Mvc.Jobs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace General.Mvc.Controllers.Admin
{
    [Route("api/admin/[controller]/[action]")]
    [ApiController]
    [ServiceFilter(typeof(ResponseLogTimeFilter))]
    public class JobController : Controller
    {
        private readonly ISchedulerFactory schedulerFactory;
        private IScheduler _scheduler;
        public JobController(ISchedulerFactory schedulerFactory)
        {
            this.schedulerFactory = schedulerFactory;
        }





        #region 定时任务
        /// <summary>
        /// 获取定时任务列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> GetJobList(int page, int limit, string name, string remark)
        {
            AdminResult result = new AdminResult();
            var list = JobListModel.list.OrderByDescending(x => x.id).ToList();
            result.count = list.Count;
            if (!string.IsNullOrWhiteSpace(name))
            {
                list = list.Where(x => x.name.Contains(name)).ToList();
            }
            if (!string.IsNullOrWhiteSpace(remark))
            {
                list = list.Where(x => x.remark.Contains(remark)).ToList();
            }
            result.data = list.Skip((page - 1) * limit).Take(limit).ToList();
            result.code = 0;
            return Content(JsonHelper.Serialize(result));
        }

        /// <summary>
        /// 添加定时任务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> AddJobInfo([FromForm] JobItemModel job, [FromForm] int jobType, [FromForm] string url)
        {
            AjaxResult result = new AjaxResult();
            var isExist = JobListModel.list.Where(x => x.name == job.name).FirstOrDefault();
            if (isExist != null)
            {
                return Content(result.Error("添加失败！已存在相同名称任务！"));
            }
            if (jobType == 1) //访问url
            {
                _scheduler = await schedulerFactory.GetScheduler();
                await _scheduler.Start();
                var trigger = TriggerBuilder.Create()
                                .WithCronSchedule(job.trigger)
                                .Build();
                var jobDetail = JobBuilder.Create<RequestUrlJob>()
                                .WithIdentity(job.name, "group")
                                .UsingJobData("url", url)
                                .Build();
                await _scheduler.ScheduleJob(jobDetail, trigger);
            }
            else if (jobType == 2) //清空日志
            {
                _scheduler = await schedulerFactory.GetScheduler();
                await _scheduler.Start();
                var trigger = TriggerBuilder.Create()
                                .WithCronSchedule(job.trigger)
                                .Build();
                var jobDetail = JobBuilder.Create<ClearSystemLogsJob>()
                                .WithIdentity(job.name, "group")
                                .Build();
                await _scheduler.ScheduleJob(jobDetail, trigger);
            }
            else
            {
                return Content(result.Error("任务类型错误！"));
            }
            JobListModel.list.Add(new JobItemModel() { id = JobListModel.Increment, createtime = DateTime.Now, name = job.name, remark = job.remark, trigger = job.trigger });
            JobListModel.Increment = JobListModel.Increment + 1;
            return Content(result.Ok("添加成功"));
        }

        /// <summary>
        /// 删除定时任务
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        [ServiceFilter(typeof(AdminCheckFilter))]
        public async Task<IActionResult> DeleteJobInfo([FromForm] string ids)
        {
            AjaxResult result = new AjaxResult();
            var arr = ids.Split(",", StringSplitOptions.RemoveEmptyEntries).Select<string, int>(x => Convert.ToInt32(x));
            foreach (var item in arr)
            {
                var temp = JobListModel.list.Where(x => x.id == item).FirstOrDefault();
                _scheduler = await schedulerFactory.GetScheduler();
                TriggerKey triggerKey = new TriggerKey(temp.name, "group");
                await _scheduler.PauseTrigger(triggerKey);//停止触发器
                await _scheduler.UnscheduleJob(triggerKey);//移除触发器
                await _scheduler.DeleteJob(new JobKey(temp.name, "group"));//删除任务
                JobListModel.list.Remove(temp);
            }
            return Content(result.Ok("删除成功"));
        }

        #endregion




    }
}
